const Router = require('koa-router')
const { resDesign } = require('@/utils/dataDesign')
const ArticleService = require('@/service/article.service')
const HTTP_CODE = require('@/app/http-code')

const articleRouter = new Router({ prefix: '/article' })

// 创建文章
articleRouter.post('/create', async (ctx) => {
  try {
    const article = ctx.request.body
    const { id } = ctx.user
    await ArticleService.createArticle(article, id)
    ctx.body = resDesign()
  } catch (error) {
    console.log(error)
    ctx.body = resDesign({ code: HTTP_CODE.error })
  }
})

// 查询文章列表
articleRouter.get('/list', async (ctx) => {
  try {
    const { id } = ctx.user
    const data = await ArticleService.selectArticle(ctx.query, id)
    ctx.body = resDesign({ data })
  } catch (error) {
    console.log(error)
  }
})

// 根据id查询文章信息和文章内容
articleRouter.get('/detail', async (ctx) => {
  try {
    const { infoId } = ctx.query
    const data = await ArticleService.selectArticleDetail(infoId)
    ctx.body = resDesign({ data })
  } catch (error) {
    console.log(error)
  }
})

// 编辑文章信息及内容
articleRouter.post('/update', async (ctx) => {
  try {
    const data = ctx.request.body
    await ArticleService.updateArticle(data)
    ctx.body = resDesign()
  } catch (error) {
    console.log(error)
    ctx.body = resDesign({ code: HTTP_CODE.error })
  }
})

// web端查询文章列表
articleRouter.get('/list/web', async (ctx) => {
  try {
    const data = await ArticleService.selectArticleListWeb(ctx.query)
    ctx.body = resDesign({ data })
  } catch (error) {
    console.log(error)
  }
})
// web端查询文章详情
articleRouter.get('/detail/web', async (ctx) => {
  try {
    const { infoId } = ctx.query
    const data = await ArticleService.selectArticleDetailWeb(infoId)
    ctx.body = resDesign({ data })
  } catch (error) {
    console.log(error)
  }
})

module.exports = articleRouter
